<template>
  <div class="table">
    <div class="content-common">
      <div class="search-top">
        <el-form :label-position="'top'" :inline="true" :model="query">
          <el-form-item label="签到日期">
            <el-date-picker placeholder="请选择" v-model="query.specificDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" :picker-options="pickerOptionsStart">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="测站">
            <el-input v-model="query.stnm" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item class="search-btn">
            <el-button
              class="table-btn-blur"
              @click="
                page.currentPage = 1;
                getData();
              "
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <div class="right-search" style="margin-top: 12px">
          <el-button class="table-btn-plain" @click="handlerExcelDownLoad">Excel导出</el-button>
          <!-- <el-button type="primary" @click="handleAdd()">新增</el-button> -->
        </div>
      </div>
      <el-table :data="tableData" :span-method="arraySpanMethod" border class="table-common" header-cell-class-name="table-header">
        <el-table-column type="index" width="55" label="序号"></el-table-column>
        <el-table-column align="center" prop="userName" label="人员姓名">
          <template #default="scope">
            <span class="titleLink" @click="handleViewDetail(scope.row)">{{ scope.row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="specificDate" label="日期"></el-table-column>
        <el-table-column align="center" prop="stnm" label="测站"></el-table-column>
        <el-table-column align="center" prop="weekDay" label="星期"></el-table-column>
        <el-table-column align="center" prop="clockInTime" label="上班打卡时间"></el-table-column>
        <el-table-column align="center" prop="clockOffTime" label="下班打卡时间"></el-table-column>
        <el-table-column align="center" prop="location" label="签到点位" :show-overflow-tooltip="true">
          <template #default="scope">
            <span class="titleLink" @click="handleShowMap(scope.row)">
              <el-icon class="icon_red" size="18">
                <Location />
              </el-icon>
              {{ scope.row.location }}</span
            >
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status" label="状态">
          <template #default="scope">
            <span v-if="isCheckdata">{{ scope.row.status }}</span>
            <span v-else-if="scope.row.status == '未签到'">{{ scope.row.status }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="danger" class="table-btn-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template> 
        </el-table-column>-->
      </el-table>
      <!-- 
      <el-row type="flex" justify="end" style="margin-top: 20px">
        <el-pagination background v-model:currentPage="page.currentPage" @current-change="getData" layout="prev,total, pager, next" :total="page.totalSize"> </el-pagination>
      </el-row> -->
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="logTitle" v-model="editVisible" width="800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="160px" label-position="top">
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="测站" prop="stnm">
              <el-select v-model="form.stnm" filterable placeholder="请选择">
                <el-option v-for="item in stationData" :key="item.stnm" :label="item.stnm" :value="item.stnm"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="签到类型" prop="clockType">
              <el-select v-model="form.clockType" filterable placeholder="请选择">
                <el-option v-for="item in clockTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="签到时间" prop="specificDate">
              <el-date-picker
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="选择时间"
                v-model="form.specificDate"
                style="width: 100%"
                :picker-options="startTimeOptions"
                ref="start"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="签到定位" prop="coordinate">
              <el-input v-model="form.coordinate" placeholder="签到定位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7"> </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看签到点位详情-->
    <el-dialog class="dialog_add_form" title="签到点位" top="2%" v-model="dialogMap.show" width="1400px" v-if="dialogMap.show" :close-on-click-modal="false">
      <GaoMap :query="dialogMap.query" @close="closeMapDialog"></GaoMap>
    </el-dialog>
  </div>
</template>

<script>
import { Location } from '@element-plus/icons-vue';
import axios from 'axios';
import detail from './detail.vue';
import GaoMap from './GaoMap.vue';
import {
  sysdictviewlistDictItem,
  viewPageStationInfo,
  pageAttendanceRecord, //分页查询
  saveAttendanceRecord, //新增编辑打卡记录
  delAttendanceRecord, //删除打卡记录
  exportAttendanceRecord, //导出打卡记录列表
  listDailyRecord //列表查询日常考勤情况（包含所有站点工作人员，未签到则没有签到详情信息）
} from '../../../api/index';
import moment from 'moment';
export default {
  name: 'zhengbianguancao',
  components: {
    detail,
    GaoMap
  },
  data() {
    return {
      tijiaorule: {
        status: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      rules: {
        stnm: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      shenpilog: false,
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        specificDate: ''
      },
      excelllog: false,
      formInline: {},
      tableData: [],
      clockTypeList: [
        { label: '上班', value: 1 },
        { label: '下班', value: 2 }
      ],
      editVisible: false,
      logTitle: '',
      pageTotal: 0,
      form: {
        clockTime: '', //打卡时间（HH:mm:ss）
        clockType: '', //打卡类型（1上班，2下班）
        coordinate: '', //签到点坐标
        id: '', //主键id
        remark: '', //备注
        specificDate: '', //日期（yyyy-MM-dd）
        stnm: '', //测站
        userCode: JSON.parse(sessionStorage.getItem('userInfo')).userNo //用户编号
      },
      stationData: [],
      checkArr: [],
      tijiaoform: {
        status: 1
      },
      selnow: {},
      startTimeOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      isView: false,
      calenderDate: new Date(),
      pickerOptionsStart: {
        disabledDate: (time) => {
          const endDateVal = new Date(this.query.endDate).getTime();
          if (endDateVal) {
            return time.getTime() > endDateVal - 0;
          }
        }
      },
      dialogMes: {
        show: false,
        query: {}
      },
      detailTitle: '',
      dialogMap: {
        show: false,
        query: {}
      },
      isCheckdata: false //roleNoList中包含JS-00000007为审批人员
    };
  },
  watch: {
    calenderDate(newVal, oldVal) {
      // 格式化 因为绑定的数组不是我们想用的，这里以2022-22-22这种格式作为演示
      let date = this.formatDate(newVal);
      this.query.specificDate = date;
      // 这里就是我们处理数据，调用接口的位置
      this.getData();
    }
  },
  created() {
    let roleCode = JSON.parse(sessionStorage.getItem('userInfo')).roleNoList.join(',');
    if (roleCode.indexOf('JS-00000007') > -1) {
      this.isCheckdata = true;
    } else {
      this.isCheckdata = false;
    }
    this.query.specificDate = new Date();
    this.query.specificDate = this.formatDate(this.query.specificDate);
    this.globalUser = globalUser;
    this.getData();
    this.getstationData();
    this.getchecktype();
  },
  methods: {
    //无打卡记录的合并列
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row.status === '未签到') {
        if (columnIndex == 0 || columnIndex == 1 || columnIndex == 2) {
          return {
            rowspan: 1,
            colspan: 1
          };
        } else if (columnIndex == 8) {
          return {
            rowspan: 1,
            colspan: 6
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    formatDate(date) {
      const value = new Date(date);
      const year = value.getFullYear();
      const month = (value.getMonth() + 1).toString().padStart(2, '0');
      const day = value.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    tomingxi(item) {
      this.form = item;
      this.logTitle = '查看打卡';
      this.editVisible = true;
    },
    getchecktype() {
      let that = this;
      sysdictviewlistDictItem({
        dictCode: 'ZD-000004'
      })
        .then((e) => {
          that.checkArr = e.object;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    shenpi(item) {
      this.tijiaoform.reviewer = item.reviewer;
      this.tijiaoform.relatedNo = item.recordNo;
      this.tijiaoform.approveType = 'R2';
      this.shenpilog = true;
      this.selnow = item;
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList.filter((item) => {
          return item.stType == systype;
        });
      });
    },
    //导出
    async handlerExcelDownLoad() {
      let url = globalVar.xiaoliuyubaseURL + '/soilWater/manage/attendance/export/exportAttendanceRecord';
      var options = {
        url: url,
        method: 'post',
        responseType: 'blob',
        headers: {
          Authorization: sessionStorage.getItem('token')
        }
      };
      axios(options).then((res) => {
        if (res) {
          const link = document.createElement('a');
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }); //生成blob对象
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          const fileName = '考勤打卡记录表';
          link.setAttribute('download', `${fileName}` + '.xlsx'); //下载的文件名以及文件格式
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          console.log('下载失败');
        }
      });
    },
    getData() {
      let that = this;
      let data = {
        currentPage: this.page.currentPage,
        pageSize: 10,
        specificDate: this.query.specificDate || ''
      };
      listDailyRecord(data).then((res) => {
        this.tableData = res.object;
        for (let i = 0; i < that.tableData.length; i++) {
          if (that.tableData[i].specificDate == null || that.tableData[i].specificDate == '') {
            that.tableData[i].specificDate = this.query.specificDate;
            that.tableData[i].status = '未签到';
          }
        }
        this.page.totalSize = res.object.length;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          delAttendanceRecord({
            id: row.id
          }).then((e) => {
            this.$message.success('删除成功');
            this.getData();
          });
        })
        .catch(() => {});
    },

    // 编辑操作
    handleEdit(row) {
      let form = row;
      form.clockType = row.recordType;
      this.logTitle = '编辑打卡';
      form.specificDate = row.recordType == 1 ? row.specificDate + ' ' + row.clockInTime : row.specificDate + ' ' + row.clockOffTime;
      this.form = form;
      this.editVisible = true;
    },
    handleAdd() {
      this.logTitle = '新增打卡';
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      let that = this;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = that.form;
          form.clockTime = that.form.specificDate.split(' ')[1];
          form.specificDate = that.form.specificDate.split(' ')[0];
          saveAttendanceRecord(form).then((e) => {
            this.editVisible = false;
            this.$message.success('操作成功');
            this.getData();
          });
        } else {
          return false;
        }
      });
    },
    //查看当前人员打卡详情
    handleViewDetail(row) {
      this.$router.push({
        path: 'checkDetail',
        query: {
          specificDate: row.specificDate,
          userName: row.userName,
          userCode: row.userCode,
          stcd: row.stcd,
          stType: row.stType
        }
      });
    },
    closeDialog() {
      this.dialogMes = {
        show: false,
        query: {}
      };
    },
    handleShowMap(row) {
      this.dialogMap = {
        show: true,
        query: {
          type: 'view',
          ...row
        }
      };
    },
    closeMapDialog() {
      this.dialogMap = {
        show: false,
        query: {}
      };
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.table-btn-plain {
  background: #fff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #3f8cff !important;
  font-size: 14px;
}
.search-btn {
  margin-top: 30px;
  width: auto !important;
}
.table-btn-blur {
  background: #3f8cff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-delete {
  background: #ff544e !important;
  border: 1px solid #ff544e !important;
  border-radius: 2px;
  color: #fff !important;
}
.titleLink {
  color: #3f8cff;
  cursor: pointer;
}

.titleLink:hover {
  text-decoration: underline;
}
/deep/.dialog_add_form {
  height: calc(100vh - 6%);
}
/deep/.dialog_add_form .el-dialog__body {
  padding: 2px;
  height: calc(100% - 44px);
}
.icon_red {
  height: 18px;
  display: block;
  color: red;
  float: left;
  cursor: pointer;
}
</style>

